/**
 *
 */
package com.dhcc.android.base.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.dhcc.android.base.common.bean.BasicProperties;
import com.dhcc.android.base.common.bean.KeyValueBean;
import com.dhcc.android.base.common.bean.PhotosBean;
import com.dhcc.android.base.utils.CommenUtil;
import com.dhcc.android.base.utils.FileUtil;
import com.dhcc.android.base.utils.StringUtil;

import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 外部db导入
 *
 * @author pengling
 * @date 2015-6-3
 */
public class DBManagerUtil {
    private static String[] columns = null;
    private static SQLiteDatabase db;
    private static String dbFilePath;
    private static WeakReference<Context> wr;
    private static DBManagerUtil instance;

    private DBManagerUtil(Context context) {
        this.wr = new WeakReference<>(context);
    }

    public static DBManagerUtil getInstance(String mDbFilePath, Context context) {
        dbFilePath = mDbFilePath;
        return new DBManagerUtil(context);
    }

    /**
     * 使用前打开数据库
     */
    public static void openDataBase(String path) {
        if (StringUtil.isEmpty(path) || !FileUtil.isExistFile(path)) {
            path = dbFilePath;
        }
        if (!path.contains("DATA.db")) {
            path = path + "DATA.db";
        }
        try {
            System.out.println("###数据库：" + path);
            db = SQLiteDatabase.openOrCreateDatabase(path, null);
            System.out.println("###获得db");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 使用前打开数据库
     */
    public static void openDataBasePhotos(String path) {
        if (StringUtil.isEmpty(path) || !FileUtil.isExistFile(path)) {
            path = dbFilePath;
        }
        if (!path.contains("PHOTO.db")) {
            path = path + "PHOTO.db";
        }
        try {
            System.out.println("###数据库：" + path);
            db = SQLiteDatabase.openOrCreateDatabase(path, null);
            System.out.println("###获得db");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据
     *
     * @param table     表名
     * @param fieldList 搜索的字段名数组
     * @param key       搜索条件对应的字段名
     * @param value     搜索条件对应的值
     * @param path      对应的数据库完整路径
     */
    public static List<Map<String, String>> getListData(String table, List<String> fieldList, String key, Object value,
                                                        String path) {
        try {
            openDataBase(path); // 打开数据
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            String fstr = "";

            if (fieldList == null || fieldList.size() == 0) {
                fstr = " * ";
                return null;
            } else {
                fieldList.add("rowid");// 主键
                for (String str : fieldList) {
                    fstr += " " + str + ",";
                }
                fstr = fstr.substring(0, fstr.length() - 1);
            }

            String wstr = "";
            if (StringUtil.isNotEmpty(key) && StringUtil.isNotEmpty(value + "")) {
                if (StringUtil.isString(value)) {// 是string
                    wstr = " WHERE " + key + " = '" + value + "'";
                } else {
                    wstr = " WHERE " + key + " = " + value + "";
                }
            }

            String sql = "SELECT " + fstr + " FROM " + table + " " + wstr;
            System.out.println("###sql:" + sql);

            Cursor c = db.rawQuery(sql, null);
            while (c.moveToNext()) {
                Map<String, String> map = new HashMap<String, String>();
                for (String str : fieldList) {
                    map.put(str, c.getString(c.getColumnIndex(str)));
                }
                list.add(map);
            }
            c.close();
            db.close();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            // CommenUtil.toast("数据库操作错误，请联系管理员", context);
        }
        return null;
    }

    /**
     * 获取数据
     *
     * @param table     表名
     * @param fieldList 搜索的字段名数组
     * @param key       搜索条件对应的字段名
     * @param value     搜索条件对应的值
     * @param filter    过滤条件
     * @param path      对应的数据库完整路径
     */
    public static List<Map<String, String>> getListData(String table, List<String> fieldList, String key, Object value,
                                                        String filter, String path) {
        try {
            openDataBase(path); // 打开数据
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            String fstr = "";

            if (fieldList == null || fieldList.size() == 0) {
                fstr = " * ";
                return null;
            } else {
                fieldList.add("rowid");// 主键
                for (String str : fieldList) {
                    fstr += " " + str + ",";
                }
                fstr = fstr.substring(0, fstr.length() - 1);
            }

            String wstr = "";
            if (StringUtil.isNotEmpty(key) && StringUtil.isNotEmpty(value + "")) {
                if (StringUtil.isString(value)) {// 是string
                    wstr = " WHERE " + key + " = '" + value + "'";
                } else {
                    wstr = " WHERE " + key + " = " + value + "";
                }
                if (StringUtil.isNotEmpty(filter)) {
                    wstr += " and " + filter;
                }
            } else {
                if (StringUtil.isNotEmpty(filter)) {
                    wstr = " where " + filter;
                }
            }

            String sql = "SELECT " + fstr + " FROM " + table + " " + wstr;
            System.out.println("###sql:" + sql);

            Cursor c = db.rawQuery(sql, null);
            while (c.moveToNext()) {
                Map<String, String> map = new HashMap<String, String>();
                for (String str : fieldList) {
                    map.put(str, c.getString(c.getColumnIndex(str)));
                }
                list.add(map);
            }
            c.close();
            db.close();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            // CommenUtil.toast("数据库操作错误，请联系管理员", context);
        }
        return null;
    }

    /**
     * 获取数据
     *
     * @param table     表名
     * @param fieldList 搜索的字段名数组
     * @param filter    搜索条件
     * @param path      对应的数据库完整路径
     */
    public static List<Map<String, String>> getListData(String table, List<String> fieldList, String filter, String path) {
        try {
            // 打开数据
            try {
                System.out.println("###数据库：" + path);
                db = SQLiteDatabase.openOrCreateDatabase(path, null);
                System.out.println("###获得db");
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }

            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            String fstr = "";

            if (fieldList == null || fieldList.size() == 0) {
                fstr = " * ";
                return null;
            } else {
                fieldList.add("rowid");// 主键
                for (String str : fieldList) {
                    fstr += " " + str + ",";
                }
                fstr = fstr.substring(0, fstr.length() - 1);
            }

            String wstr = "";
            if (StringUtil.isNotEmpty(filter)) {
                wstr = " WHERE " + filter;
            }

            String sql = "SELECT " + fstr + " FROM " + table + " " + wstr;
            System.out.println("###sql:" + sql);

            Cursor c = db.rawQuery(sql, null);
            while (c.moveToNext()) {
                Map<String, String> map = new HashMap<String, String>();
                for (String str : fieldList) {
                    map.put(str, c.getString(c.getColumnIndex(str)));
                }
                list.add(map);
            }
            c.close();
            db.close();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            // CommenUtil.toast("数据库操作错误，请联系管理员", context);
        }
        return null;
    }

    /**
     * 保存多条数据
     *
     * @param datas     要保存的数据
     * @param fieldList 对应的字段名
     * @param table     表名
     * @param key       【传一个空字符串即可】
     * @param path      数据库完整路径
     */
    public static boolean add(List<Map<String, String>> datas, List<String> fieldList, String table, String key,
                              KeyValueBean kv, String path) {
        openDataBase(path); // 打开数据
        db.beginTransaction();
        try {
            for (Map<String, String> map : datas) {
                ContentValues values = new ContentValues();
                for (String str : fieldList) {
                    if (map.containsKey(str)) {
                        values.put(str, map.get(str));
                    }
                }
                values.put(kv.getKey(), kv.getValue());
                db.insert(table, key, values);
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }

        return true;
    }

    /**
     * 保存多条数据 ----选择添加列表
     *
     * @param datas     要保存的数据
     * @param fieldList 对应的字段名
     * @param table     表名
     * @param pkv       外键 对应当前层级对象的属性 check
     * @param jcfields  要继承的字段列表
     * @param parent    当前对应的地块对象
     * @param path      数据库完整路径
     */
    public static boolean add(List<Map<String, String>> datas, List<String> fieldList, String table, KeyValueBean pkv,
                              List<KeyValueBean> jcfields, Map<String, String> parent, String path) {
        openDataBase(path); // 打开数据
        db.beginTransaction();
        try {
            // 清空数据
            String sql = "delete from " + table + " where " + pkv.getKey() + " = '" + parent.get(pkv.getValue()) + "'";
            db.execSQL(sql);

            // 去除rowid
            fieldList.remove("rowid");
            // 添加
            for (Map<String, String> map : datas) {
                ContentValues values = new ContentValues();
                for (String str : fieldList) {
                    if (map.containsKey(str)) {
                        values.put(str, map.get(str));
                    }
                }
                for (KeyValueBean kv : jcfields) {
                    // 判断继承类型
                    if (kv.getType() == 1) {
                        if (parent.containsKey(kv.getValue())) {
                            values.put(kv.getKey(), parent.get(kv.getValue()));
                        }

                    } else if (kv.getType() == 2) {
                        if (parent.containsKey(kv.getValue())) {
                            String val = parent.get(kv.getValue());
                            int v = Integer.parseInt(val) + 1;
                            values.put(kv.getKey(), String.valueOf(v));
                        }
                    }
                }

                db.insert(table, "", values);
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }

        return true;
    }

    /**
     * 保存多条数据 ----选择添加列表--设施农业用地
     *
     * @param yfbhu     样本编号
     * @param datas     要保存的数据
     * @param fieldList 对应的字段名
     * @param fixkey    固定的键
     * @param table     表名
     * @param pkv       外键 对应当前层级对象的属性 check
     * @param jcfields  要继承的字段列表
     * @param parent    当前对应的地块对象
     * @param path      数据库完整路径
     */
    public static boolean add(String yfbhu, List<Map<String, String>> datas, List<String> fieldList, String table,
                              KeyValueBean pkv, List<KeyValueBean> jcfields, Map<String, String> parent, String path) {
        openDataBase(path); // 打开数据
        db.beginTransaction();
        try {
            // 清空数据
            String sql = "delete from " + table + " where " + pkv.getKey() + " = '" + parent.get(pkv.getValue()) + "'";
            db.execSQL(sql);

            // 去除rowid
            fieldList.remove("rowid");
            // 添加
            for (Map<String, String> map : datas) {
                ContentValues values = new ContentValues();
                for (String str : fieldList) {
                    if (map.containsKey(str)) {
                        values.put(str, map.get(str));
                    }
                }
                for (KeyValueBean kv : jcfields) {
                    // 判断继承类型
                    if (kv.getType() == 1) {
                        if (parent.containsKey(kv.getValue())) {
                            values.put(kv.getKey(), parent.get(kv.getValue()));
                        }

                    } else if (kv.getType() == 2) {
                        if (parent.containsKey(kv.getValue())) {
                            String val = parent.get(kv.getValue());
                            int v = Integer.parseInt(val) + 1;
                            values.put(kv.getKey(), String.valueOf(v));
                        }
                    }
                }
                // 设置固定的键值
                values.put("YFBHU", yfbhu);

                db.insert(table, "", values);
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }

        return true;
    }

    /**
     * 添加一条无作物 的 设施 数据
     */
    public static boolean add(String yfbhu, String dkbhu, String sslx, String mj, String table, String path) {
        openDataBase(path); // 打开数据
        db.beginTransaction();
        try {
            // 清空数据
            String sql = "delete from " + table + " where  DKBHU= '" + dkbhu + "'";
            db.execSQL(sql);

            // 添加
            ContentValues values = new ContentValues();
            values.put("DKBHU", dkbhu);
            values.put("YFBHU", yfbhu);
            values.put("SNYD", sslx);
            values.put("SNZWMJ", mj);

            db.insert(table, "", values);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }

        return true;
    }

    public static boolean deleteByFilter(String table, String filter, String path) {
        try {
            openDataBase(path);
            db.beginTransaction();
            String sql = "";
            if (StringUtil.isString(filter)) {// 是string
                sql = "DELETE FROM " + table + " where " + filter;
            } else {
                return false;
            }
            System.out.println("-delete-:" + sql);
            db.execSQL(sql);
            db.setTransactionSuccessful();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.endTransaction();
            db.close();
        }

        return true;
    }

    /**
     * @param currentNum
     * @param table      表
     * @param path       路径
     * @return
     */
    public static int getRowId(int currentNum, String table, String path) {
        int rowid = 0;
        openDataBase(path); // 打开数据
        try {
            String sql = null;
            sql = "SELECT rowid FROM " + table + " LIMIT " + currentNum + " , 1";
            Cursor c = db.rawQuery(sql, null);
            while (c.moveToNext()) {
                rowid = c.getInt(c.getColumnIndex("rowid"));
            }
            c.close();
        } finally {
            db.close();
        }

        db.close();

        return rowid;
    }

    /**
     * 增加一条记录
     *
     * @param map
     * @param fieldList key值
     * @param table     表名
     * @param key
     * @param path
     * @return
     */
    public static boolean add(Map<String, String> map, List<String> fieldList, String table, String key, String path) {
        openDataBase(path); // 打开数据
        System.out.println("addMap:--" + map);
        db.beginTransaction();
        try {
            ContentValues values = new ContentValues();
            for (String str : fieldList) {
                if (map.containsKey(str)) {
                    values.put(str, map.get(str));
                }
            }
            db.insert(table, key, values);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
        return true;
    }

    /**
     * 删除一条记录
     *
     * @param table 表名
     * @param pId   为主键
     * @param key   主键字段名
     * @return
     */
    public static boolean deleteById(String table, String key, Object pId, String path) {
        boolean flag = true;
        try {
            openDataBase(path);
            String sql = "";
            if (StringUtil.isString(pId)) {// 是string
                sql = "DELETE FROM " + table + " where " + key + "='" + pId + "'";
            } else {
                sql = "DELETE FROM " + table + " where " + key + "=" + pId + "";
            }
            System.out.println("-delete-:" + sql);
            db.execSQL(sql);

        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        } finally {
            db.close();
        }

        return flag;
    }

    /**
     * 修改一条记录
     *
     * @param map       数据对象
     * @param fieldList 字段集合
     * @param table     表名
     * @param key       条件 key
     * @param value     条件 value
     * @param path      数据库完整路径
     * @return
     */
    public static boolean updateById(Map<String, String> map, List<String> fieldList, String table, String key, String value,
                                     String path) {
        openDataBase(path); // 打开数据
        db.beginTransaction();
        try {
            ContentValues values = new ContentValues();
            for (String str : fieldList) {
                if (map.containsKey(str)) {
                    values.put(str, map.get(str));
                }
            }
            // if(StringUtil.isString(pId)){//是string
            // db.update(table, values, key+"=?", new String[] { pId });
            // }else{
            // db.update(table, values, key+"=?", new Interger[] { pId });
            // }
            db.update(table, values, key + "=?", new String[]{value});
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
        return true;
    }

    /**
     * 修改一条记录,地图新增，编辑专用
     *
     * @param table     表名
     * @param pId       为主键
     * @param fieldList key值
     * @param table     表名
     * @param key       主键字段名
     * @return
     */
    public static boolean updateByIdForGeo(Map<String, String> map, List<String> fieldList, String table, String key,
                                           int value, String path) {
        openDataBase(path); // 打开数据
        db.beginTransaction();
        try {
            String sql = "UPDATE FROM " + table + " where " + key + "=" + value + "";
            db.execSQL(sql);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
        return true;
    }

    /**
     * 修改一条记录
     *
     * @param table     表名
     * @param pId       为主键
     * @param fieldList key值
     * @param table     表名
     * @param key       主键字段名
     * @return
     */
    public static boolean replaceById(Map<String, String> map, List<String> fieldList, String table, String key, String path) {
        openDataBase(path); // 打开数据
        db.beginTransaction();
        try {
            ContentValues values = new ContentValues();
            for (String str : fieldList) {
                if (map.containsKey(str)) {
                    values.put(str, map.get(str));
                }
            }
            db.replace(table, key, values);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
        return true;
    }

    /**
     * 获取数据对应的行号
     */
    public static int getRowId(String table, String key, String value, String path) {
        openDataBase(path);
        int row = 0;
        String sql = "select rowid from " + table + " where " + key + " = '" + value + "'";

        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            row = c.getInt(c.getColumnIndex("rowid"));
        }
        c.close();
        db.close();
        return row;
    }

    /**
     * 得到记录的总数
     *
     * @param path
     * @param table 表名
     * @param key   主键
     * @param value 值
     * @return
     */
    public static int getCount(String path, String table, String key, String value) {
        openDataBase(path); // 打开数据
        int size = 0;
        String sql = "";
        if (StringUtil.isEmpty(key)) {
            sql = "select count(*) as size from " + table;
        } else {
            sql = "select count(*) as size from " + table + " where " + key + " = '" + value + "'";
        }
        System.out.println("-sql-:" + sql);
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            size = c.getInt(c.getColumnIndex("size"));
        }
        c.close();
        db.close();
        return size;
    }

    /**
     * 得到照片的总数
     *
     * @param path
     * @param table 表名
     * @param key   主键
     * @param value 值
     * @param type  类型
     * @return
     */
    public static int getPhotoCount(String path, String table, String key, String value, String type) {
        openDataBase(path); // 打开数据
        int size = 0;
        String sql = "";
        if (StringUtil.isEmpty(key)) {
            sql = "select count(*) as size from " + table + " where 备注  = '" + type + "'";
        } else {
            sql = "select count(*) as size from "
                    + table
                    + " where 备注  = '"
                    + type
                    + "' and "
                    + key
                    + " = '"
                    + value
                    + "'";
        }
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            size = c.getInt(c.getColumnIndex("size"));
        }
        c.close();
        db.close();
        return size;
    }

    /**
     * 增加一条记录
     *
     * @param table       表名
     * @param photosBeans 照片实体类集合
     * @param path        数据库绝对路径
     * @return
     */
    public static boolean addValues(String table, List<PhotosBean> photosBeans, String path) {
        openDataBasePhotos(path); // 打开数据
        db.beginTransaction();
        StringBuffer stringBuffer = null;
        String sqlVaules = null;
        try {
            stringBuffer = new StringBuffer(" values (?, ?, ?, ?, ");

            System.out.println("@@@@" + stringBuffer.toString());
            System.out.println("@@@@" + (photosBeans.get(0).getMarkList().size() - 1));

            for (int i = 0; i < (photosBeans.get(0).getMarkList().size() - 1); i++) {
                sqlVaules = stringBuffer.append("?, ").toString();
            }
            sqlVaules = sqlVaules + "?)";

            System.out.println("@@@@" + sqlVaules.toString());

            String sql = "insert into " + table + sqlVaules;

            System.out.println("@@@@" + sql.toString());

            for (int i = 0; i < photosBeans.size(); i++) {
                db.execSQL(sql, beanToStrs(photosBeans.get(i)));
            }
            /*
             * stringBuffer = null;
             * sqlVaules = null;
             */
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
        return true;
    }

    /**
     * 增加一条记录
     *
     * @param table       表名
     * @param photosBeans 照片实体类集合
     * @param path        数据库绝对路径
     * @return
     */
    public static boolean addValues2(String table, List<PhotosBean> photosBeans, List<String> keyList, String path) {
        openDataBasePhotos(path); // 打开数据
        db.beginTransaction();
        String keyString = null;
        // String[] strings = getColumnNameAndCount(path, table, null, null);
        try {
            ContentValues values = null;
            for (int i = 0; i < photosBeans.size(); i++) {
                values = new ContentValues();
                /*
                 * System.out.println("@@@@str:"+keyList.get(0));
                 * System.out.println("@@@@str2:"+photosBeans.get(i).getMarkMap().toString());
                 */
                values.put("FILENAME", photosBeans.get(i).getPhotoFileName());
                values.put("LON", photosBeans.get(i).getPhotoLon());
                values.put("LAT", photosBeans.get(i).getPhotoLat());
                values.put("DATE", photosBeans.get(i).getPhotoDate());
                for (String str : keyList) {
                    if (photosBeans.get(i).getMarkMap().containsKey(str)) {
                        /* System.out.println("@@@@str:"+str+"====values"+photosBeans.get(i).getMarkMap().get(str)); */
                        values.put(str, photosBeans.get(i).getMarkMap().get(str));
                    }
                }
                db.insert(table, keyString, values);
            }

            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
        return true;
    }

    /**
     * 删除一条记录
     *
     * @param table
     * @param key
     * @param pId
     * @param path
     * @return
     */
    public static boolean deleteByKey(String table, Object pId, String path) {
        try {
            openDataBasePhotos(path); // 打开数据
            String sql;
            if (StringUtil.isString(pId)) {// 是string
                sql = "DELETE FROM " + table + " where FILENAME='" + pId + "'";
            } else {
                sql = "DELETE FROM " + table + " where FILENAME=" + pId + "";
            }
            db.execSQL(sql);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.close();
        }

        return true;
    }

    /**
     * 得到记录总条数
     *
     * @param path  数据库路径
     * @param table 表名
     * @param key   字段名
     * @param value 值
     * @return
     */
    public static int getPhotoInfoCount(String path, String table, String key, String value) {
        openDataBasePhotos(path); // 打开数据
        int size = 0;
        String sql = "";
        if (StringUtil.isEmpty(key)) {
            sql = "select count(*) as size from " + table;
        } else {
            sql = "select count(*) as size from " + table + " where " + key + " = '" + value + "'";
        }
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            size = c.getInt(c.getColumnIndex("size"));
        }
        c.close();
        db.close();
        return size;
    }

    /**
     * 查询列名
     *
     * @param path
     * @param table
     * @param key
     * @param value
     * @return
     */
    public static String[] getColumnNameAndCount(String path, String table, String key, String value) {
        openDataBasePhotos(path); // 打开数据
        int size = 0;
        String sql = "";
        if (StringUtil.isEmpty(key)) {
            sql = "select count(*) as size from " + table;
        } else {
            sql = "select count(*) as size from " + table + " where " + key + " = '" + value + "'";
        }
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            size = c.getInt(c.getColumnIndex("size"));
        }
        columns = c.getColumnNames();
        c.close();
        db.close();
        return columns;
    }

    /**
     * 照片信息实体类转化为String数组
     *
     * @param pBn 实体类
     * @return String数组
     */
    public static String[] beanToStrs(PhotosBean pBn) {
        String[] values = new String[pBn.getMarkList().size() + 4];
        values[0] = pBn.getPhotoFileName();
        values[1] = pBn.getPhotoLat();
        values[2] = pBn.getPhotoLon();
        values[3] = pBn.getPhotoDate();
        for (int i = 4; i < values.length; i++) {
            values[i] = pBn.getMarkList().get(i - 4);
        }
        return values;
    }

    // =============================================================

    /**
     * 增加一条记录
     */
    public static boolean addTwoTable(String table, String ltable, Map<String, String> map, List<BasicProperties> fieldList,
                                      String path) {
        openDataBase(path); // 打开数据
        System.out.println("addMap:--" + map);
        db.beginTransaction();
        try {
            ContentValues cv1 = new ContentValues();
            ContentValues cv2 = new ContentValues();
            for (BasicProperties bp : fieldList) {
                if (map.containsKey(bp.getName())) {
                    cv1.put(bp.getName(), map.get(bp.getName()));
                    // 是否是备份表的字段
                    if (StringUtil.isNotEmpty(bp.getRepeat()) && bp.getRepeat().equals("1")) {
                        cv2.put(bp.getName(), map.get(bp.getName()));
                    }
                }
            }
            db.insert(table, "", cv1);
            db.insert(ltable, "", cv2);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
        return true;
    }

    /**
     * 修改两个表
     */
    public static boolean updateTwoTable(String table, String ltable, Map<String, String> map,
                                         List<BasicProperties> fieldList, String rowid, String path) {
        openDataBase(path); // 打开数据
        db.beginTransaction();
        try {
            ContentValues cv1 = new ContentValues();
            ContentValues cv2 = new ContentValues();
            for (BasicProperties bp : fieldList) {
                if (map.containsKey(bp.getName())) {
                    cv1.put(bp.getName(), map.get(bp.getName()));
                    // 是否是备份表的字段
                    if (StringUtil.isNotEmpty(bp.getRepeat()) && bp.getRepeat().equals("1")) {
                        cv2.put(bp.getName(), map.get(bp.getName()));
                    }
                }
            }
            db.update(table, cv1, "rowid = ?", new String[]{rowid});
            db.update(ltable, cv2, "rowid = ?", new String[]{rowid});
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
        return true;
    }

    /**
     * 删除两个表
     */
    public static boolean deleteTwoTable(String table, String ltable, String key, Object pId, String path) {

        openDataBase(path);
        db.beginTransaction();
        try {
            String sql1 = "";
            String sql2 = "";
            if (StringUtil.isString(pId)) {// 是string
                sql1 = "DELETE FROM " + table + " where " + key + "='" + pId + "'";
                sql2 = "DELETE FROM " + ltable + " where " + key + "='" + pId + "'";
            } else {
                sql1 = "DELETE FROM " + table + " where " + key + "=" + pId + "";
                sql2 = "DELETE FROM " + ltable + " where " + key + "=" + pId + "";
            }
            db.execSQL(sql1);
            db.execSQL(sql2);

            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            db.endTransaction();
            db.close();
        }

        return true;
    }

    /**
     * 获取最大的 DKBHU
     */
    public static String getLastDKBHU(String table, String key, String value, String path) {
        String dkbhu = null;
        openDataBase(path);
        String sql = "select DKBHU from " + table + " where " + key + " = '" + value + "' order by DKBHU desc";
        System.out.println("sql:" + sql);
        Cursor c = db.rawQuery(sql, null);
        if (c.moveToFirst()) {
            dkbhu = c.getString(c.getColumnIndex("DKBHU"));
        }
        c.close();
        db.close();

        return dkbhu;
    }

    /**
     * 获取最大的 YFDKBH
     */
    public int getLastYFDKBH(String table, String key, String value, String path) {
        int YFDKBH = 0;
        openDataBase(path);
        String sql = "select YFDKBH from " + table + " where " + key + " = '" + value + "' order by YFDKBH desc";
        System.out.println("sql:" + sql);
        Cursor c = db.rawQuery(sql, null);
        if (c.moveToFirst()) {
            YFDKBH = c.getInt(c.getColumnIndex("YFDKBH"));
        }
        c.close();
        db.close();

        return YFDKBH;
    }

    /**
     * 修改调查状态
     */
    public static boolean changeComplete(String table, String DKBHU, String path) {
        openDataBase(path); // 打开数据
        db.beginTransaction();
        try {
            ContentValues cv = new ContentValues();
            cv.put("COMPLETE", "1");
            db.update(table, cv, "DKBHU = ?", new String[]{DKBHU});
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
        System.out.println("--" + DKBHU + "--调查完成了");
        return true;
    }

    /**
     * 获取图纸拍摄数量
     */
    public static int getTZPhotoCount(String table, String where, String path) {
        openDataBase(path); // 打开数据
        int size = 0;
        String sql = "";
        if (StringUtil.isEmpty(where)) {
            sql = "select count(*) as size from " + table;
        } else {
            sql = "select count(*) as size from " + table + " where " + where;
        }
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            size = c.getInt(c.getColumnIndex("size"));
        }
        c.close();
        db.close();
        return size;
    }

    /**
     * 获取村样方数量
     */
    public static int getCYFCount(String table, String where, String path) {
        openDataBase(path); // 打开数据
        int size = 0;
        String sql = "";
        if (StringUtil.isEmpty(where)) {
            sql = "select count(*) as size from " + table;
        } else {
            sql = "select count(*) as size from " + table + " where " + where;
        }
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            size = c.getInt(c.getColumnIndex("size"));
        }
        c.close();
        db.close();
        return size;
    }

    /**
     * 获取数据表--字符串集合
     *
     * @param table
     * @param key
     * @param filer
     * @param path
     */
    public static List<String> getListDatas(String table, String key, String filter, String path) {
        List<String> list = new ArrayList<String>();
        try {
            // 打开数据
            try {
                System.out.println("###数据库：" + path);
                db = SQLiteDatabase.openOrCreateDatabase(path, null);
                System.out.println("###获得db");
            } catch (Exception e) {
                e.printStackTrace();
                return list;
            }

            String sql = "select " + key + " from " + table;
            if (StringUtil.isNotEmpty(filter)) {
                sql += " where " + filter;
            }
            System.out.println("--sql:" + sql);

            Cursor c = db.rawQuery(sql, null);
            while (c.moveToNext()) {
                list.add(c.getString(c.getColumnIndex(key)));
            }

            c.close();
            db.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 获取数据表--KeyValueBean集合
     *
     * @param table
     * @param kv
     * @param filer
     * @param path
     */
    public static List<KeyValueBean> getListDatas(String table, KeyValueBean kv, String filter, String path) {
        List<KeyValueBean> list = new ArrayList<KeyValueBean>();
        try {
            // 打开数据
            try {
                System.out.println("###数据库：" + path);
                db = SQLiteDatabase.openOrCreateDatabase(path, null);
                System.out.println("###获得db");
            } catch (Exception e) {
                e.printStackTrace();
                return list;
            }

            String sql = "select * from " + table;
            if (StringUtil.isNotEmpty(filter)) {
                sql += " where " + filter;
            }
            System.out.println("--sql:" + sql);

            Cursor c = db.rawQuery(sql, null);
            while (c.moveToNext()) {
                String key = c.getString(c.getColumnIndex(kv.getKey()));
                String value = c.getString(c.getColumnIndex(kv.getValue()));
                list.add(new KeyValueBean(key, value));
            }

            c.close();
            db.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 获取数据
     *
     * @param table     表名
     * @param fieldList 搜索的字段名数组
     * @param key       搜索条件对应的字段名
     * @param value     搜索条件对应的值
     * @param filter    过滤条件
     * @param path      对应的数据库完整路径
     * @param mjkey
     */
    public static List<Map<String, String>> getMixListData(String table, List<String> fieldList, String key, Object value,
                                                           String filter, String path, String mjkey) {
        try {
            openDataBase(path); // 打开数据
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            String fstr = "";

            if (fieldList == null || fieldList.size() == 0) {
                fstr = " * ";
                return null;
            } else {
                fieldList.add("rowid");// 主键
                for (String str : fieldList) {
                    fstr += " " + str + ",";
                }
                fstr = fstr.substring(0, fstr.length() - 1);
            }

            String wstr = "";
            if (StringUtil.isNotEmpty(key) && StringUtil.isNotEmpty(value + "")) {
                if (StringUtil.isString(value)) {// 是string
                    wstr = " WHERE " + key + " = '" + value + "'";
                } else {
                    wstr = " WHERE " + key + " = " + value + "";
                }
                if (StringUtil.isNotEmpty(filter)) {
                    wstr += " and " + filter;
                }
            } else {
                if (StringUtil.isNotEmpty(filter)) {
                    wstr = " where " + filter;
                }
            }

            String sql = "SELECT " + fstr + " FROM " + table + " " + wstr;
            System.out.println("###sql:" + sql);

            Cursor c = db.rawQuery(sql, null);
            while (c.moveToNext()) {
                Map<String, String> map = new HashMap<String, String>();
                for (String str : fieldList) {
                    map.put(str, c.getString(c.getColumnIndex(str)));
                    if (str.equals(mjkey)) {
                        map.put("MJPFM", CommenUtil.MUtoPFM(c.getString(c.getColumnIndex(str))));
                    }
                }
                list.add(map);
            }
            c.close();
            db.close();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            // CommenUtil.toast("数据库操作错误，请联系管理员", context);
        }
        return null;
    }

    // =======================预产================================

    /**
     * 获取面积调查数据
     *
     * @param table
     * @param path
     */
    public static List<Map<String, String>> getResearchDatas(String zwtable, String sstable, String path) {
        try {
            openDataBase(path); // 打开数据
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();

            // 1、获取作物表数据
            String sql = "SELECT YFBHU,ZWBH,ZW AS ZWMC,SUM(ZWMJ) AS ZWMJ FROM "
                    + zwtable
                    + " where ZWBH like '1%' group by YFBHU, ZW";
            System.out.println("--sql--:" + sql);
            Cursor c = db.rawQuery(sql, null);
            while (c.moveToNext()) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("YFBHU", c.getString(c.getColumnIndex("YFBHU")));
                map.put("ZWBH", c.getString(c.getColumnIndex("ZWBH")));
                map.put("ZWMC", c.getString(c.getColumnIndex("ZWMC")));
                map.put("ZWMJ", c.getString(c.getColumnIndex("ZWMJ")));

                list.add(map);
            }

            // 2、获取设施表数据
            List<Map<String, String>> sslist = new ArrayList<Map<String, String>>();
            sql = "SELECT YFBHU,SNZWBH,SNZWMC AS ZWMC,SUM(SNZWMJ) AS ZWMJ FROM "
                    + sstable
                    + " where SNZWBH like '1%' group by YFBHU, SNZWMC";
            System.out.println("--sql--:" + sql);
            c = db.rawQuery(sql, null);
            while (c.moveToNext()) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("YFBHU", c.getString(c.getColumnIndex("YFBHU")));
                map.put("ZWBH", c.getString(c.getColumnIndex("SNZWBH")));
                map.put("ZWMC", c.getString(c.getColumnIndex("ZWMC")));
                map.put("ZWMJ", c.getString(c.getColumnIndex("ZWMJ")));

                sslist.add(map);
            }
            c.close();
            db.close();

            // 3、去重
            List<Map<String, String>> templist = new ArrayList<Map<String, String>>();
            for (int i = 0; i < list.size(); i++) {
                Map<String, String> zw = list.get(i);
                for (int j = 0; j < sslist.size(); j++) {
                    Map<String, String> ss = sslist.get(j);

                    if (zw.get("YFBHU").equals(ss.get("YFBHU")) && zw.get("ZWBH").equals(ss.get("ZWBH"))) {
                        String total = getMJTOTAL(zw.get("ZWMJ"), ss.get("ZWMJ"));
                        zw.put("ZWMJ", total);
                        templist.add(zw);

                        list.remove(i);
                        sslist.remove(j);

                        i = i - 1;

                        break;
                    }
                }
            }

            // 4、整合
            if (templist.size() > 0) {
                list.addAll(templist);
            }
            if (sslist.size() > 0) {
                list.addAll(sslist);
            }

            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 计算面积之和
     */
    private static String getMJTOTAL(String mj1, String mj2) {
        double d = Double.valueOf(mj1) + Double.valueOf(mj2);
        DecimalFormat df = new DecimalFormat("######0.00");
        return df.format(d);
    }

    /**
     * 保存调查数据
     */
    public static void
    saveResearchDatasFORYC(String dcq, String tb, List<Map<String, String>> datas, String table, String path) {
        openDataBase(path); // 打开数据
        db.beginTransaction();
        try {
            for (Map<String, String> map : datas) {
                ContentValues values = new ContentValues();
                values.put("YFBHU", map.get("YFBHU"));
                values.put("ZWBH", map.get("ZWBH"));
                values.put("ZWMC", map.get("ZWMC"));
                values.put("ZWMJ", map.get("ZWMJ"));
                values.put("DCQ", dcq);
                values.put("TB", tb);

                db.insert(table, "", values);
            }

            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
    }

    /**
     * 获取预产数据列表
     *
     * @param table
     * @param path
     */
    public static List<Map<String, String>> getYCListDatas(String table, String path, String yfbhu) {
        try {
            openDataBase(path); // 打开数据
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();

            String sql = "SELECT * FROM " + table + " where YFBHU='" + yfbhu + "'";
            System.out.println("--sql--:" + sql);

            Cursor c = db.rawQuery(sql, null);
            while (c.moveToNext()) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("YFBHU", c.getString(c.getColumnIndex("YFBHU")));
                map.put("ZWBH", c.getString(c.getColumnIndex("ZWBH")));
                map.put("ZWMC", c.getString(c.getColumnIndex("ZWMC")));
                map.put("ZWMJ", c.getString(c.getColumnIndex("ZWMJ")));
                map.put("ZWCL", c.getString(c.getColumnIndex("ZWCL")));

                list.add(map);
            }
            c.close();
            db.close();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 预产填报保存
     */
    public static boolean ycSave(List<Map<String, String>> datas, String table, String path, String yfbhu) {
        openDataBase(path);
        db.beginTransaction();
        try {

            for (Map<String, String> map : datas) {
                ContentValues values = new ContentValues();
                values.put("ZWCL", map.get("ZWCL"));

                db.update(table, values, "YFBHU = ? and ZWBH = ?", new String[]{yfbhu, map.get("ZWBH")});
            }

            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }

        return true;
    }

    /**
     * 获取数据表--KeyValueBean集合
     *
     * @param table
     * @param kv
     * @param filer
     * @param path
     */
    public static List<KeyValueBean> getZWDatas(String table, KeyValueBean kv, String filter, String path) {
        List<KeyValueBean> list = new ArrayList<KeyValueBean>();
        try {
            // 打开数据
            try {
                System.out.println("###数据库：" + path);
                db = SQLiteDatabase.openOrCreateDatabase(path, null);
                System.out.println("###获得db");
            } catch (Exception e) {
                e.printStackTrace();
                return list;
            }

            String sql = "select * from " + table;
            if (StringUtil.isNotEmpty(filter)) {
                sql += " where " + filter;
            }
            System.out.println("--sql:" + sql);

            Cursor c = db.rawQuery(sql, null);
            while (c.moveToNext()) {
                String key = c.getString(c.getColumnIndex(kv.getKey()));
                String value = c.getString(c.getColumnIndex(kv.getValue()));
                String cls = c.getString(c.getColumnIndex(kv.getFieldset()));
                list.add(new KeyValueBean(key, value, cls));
            }

            c.close();
            db.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    // ===============估产======================

    /**
     * 得到记录的总数
     *
     * @param path
     * @param table 表名
     * @param key   主键
     * @param value 值
     * @return
     */
    public static int getCount(String path, String table, String filter) {
        openDataBase(path); // 打开数据
        int size = 0;
        String sql = "";
        if (StringUtil.isEmpty(filter)) {
            sql = "select count(*) as size from " + table;
        } else {
            sql = "select count(*) as size from " + table + " where " + filter;
        }
        System.out.println("-sql-:" + sql);
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            size = c.getInt(c.getColumnIndex("size"));
        }
        c.close();
        db.close();
        return size;
    }

    /**
     * 保存调查数据-作物
     */
    public static void saveZWResearchDatasFORGC(String dcq, String tb, List<Map<String, String>> datas, String table,
                                                String path) {
        openDataBase(path); // 打开数据
        db.beginTransaction();
        try {
            for (Map<String, String> map : datas) {
                ContentValues values = new ContentValues();
                values.put("YFBHU", map.get("YFBHU"));
                values.put("DKBHU", map.get("DKBHU"));
                values.put("YFDKBH", map.get("PID"));
                values.put("ZWBH", map.get("ZWBH"));
                values.put("ZWMC", map.get("ZW"));
                values.put("ZWMJ", map.get("ZWMJ"));
                values.put("DCQ", dcq);
                values.put("TB", tb);

                db.insert(table, "", values);
            }

            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
    }

    /**
     * 保存调查数据-设施
     */
    public static void saveSSResearchDatasFORGC(String dcq, String tb, List<Map<String, String>> datas, String table,
                                                String path) {
        openDataBase(path); // 打开数据
        db.beginTransaction();
        try {
            for (Map<String, String> map : datas) {
                ContentValues values = new ContentValues();
                values.put("YFBHU", map.get("YFBHU"));
                values.put("DKBHU", map.get("DKBHU"));

                String pid = map.get("DKBHU");
                String s = pid.substring(pid.length() - 4);
                int n = Integer.valueOf(s);
                values.put("YFDKBH", String.valueOf(n));

                values.put("ZWBH", map.get("SNZWBH"));
                values.put("ZWMC", map.get("SNZWMC"));
                values.put("ZWMJ", map.get("SNZWMJ"));
                values.put("DCQ", dcq);
                values.put("TB", tb);

                db.insert(table, "", values);
            }

            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
    }

    /**
     * 获取估产数据列表
     *
     * @param table
     * @param path
     */
    public static List<Map<String, String>> getGCListDatas(String table, String path, String yfbhu,
                                                           List<Map<String, String>> zwlist) {
        try {
            openDataBase(path); // 打开数据
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();

            String zwfilter = "";
            for (Map<String, String> map : zwlist) {
                zwfilter += " ZWMC='" + map.get("ZWMC") + "' OR";
            }
            System.out.println("--zwfilter--:" + zwfilter);
            zwfilter = zwfilter.substring(0, zwfilter.length() - 2);

            String sql = "SELECT * FROM "
                    + table
                    + " where  YFBHU='"
                    + yfbhu
                    + "' and ("
                    + zwfilter
                    + ") group by DKBHU ,ZWMC";
            System.out.println("--sql--:" + sql);

            Cursor c = db.rawQuery(sql, null);
            while (c.moveToNext()) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("YFBHU", c.getString(c.getColumnIndex("YFBHU")));
                map.put("DKBHU", c.getString(c.getColumnIndex("DKBHU")));
                map.put("YFDKBH", c.getString(c.getColumnIndex("YFDKBH")));
                map.put("ZWBH", c.getString(c.getColumnIndex("ZWBH")));
                map.put("ZWMC", c.getString(c.getColumnIndex("ZWMC")));
                map.put("ZWMJ", c.getString(c.getColumnIndex("ZWMJ")));
                map.put("ZWCL", c.getString(c.getColumnIndex("ZWCL")));

                list.add(map);
            }
            c.close();
            db.close();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 估产填报保存
     */
    public static boolean gcSave(List<Map<String, String>> datas, String table, String path, String yfbhu) {
        openDataBase(path);
        db.beginTransaction();
        try {

            for (Map<String, String> map : datas) {
                ContentValues values = new ContentValues();
                values.put("ZWCL", map.get("ZWCL"));

                db.update(table, values, "YFBHU = ? and DKBHU = ? and ZWBH = ?", new String[]{
                        yfbhu, map.get("DKBHU"), map.get("ZWBH")});
            }

            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }

        return true;
    }

    // ===========================实割实测================================

    /**
     * 获取实割实测数据
     *
     * @param table
     * @param path
     */
    public static Map<String, String> getSGSCData(String table, String path, String zwbh, String yfbhu, String dkbhu) {
        try {
            openDataBase(path); // 打开数据
            Map<String, String> map = null;

            String sql = "SELECT * FROM "
                    + table
                    + " where ZWBH='"
                    + zwbh
                    + "' AND YFBHU='"
                    + yfbhu
                    + "' AND DKBHU='"
                    + dkbhu
                    + "'";
            System.out.println("--sql--:" + sql);

            Cursor c = db.rawQuery(sql, null);
            if (c.moveToFirst()) {
                map = new HashMap<String, String>();
                map.put("YFBHU", c.getString(c.getColumnIndex("YFBHU")));
                map.put("DKBHU", c.getString(c.getColumnIndex("DKBHU")));
                map.put("ZWBH", c.getString(c.getColumnIndex("ZWBH")));
                map.put("ZWMC", c.getString(c.getColumnIndex("ZWMC")));
                map.put("YBFYSL", c.getString(c.getColumnIndex("YBFYSL")));
                map.put("YBMJ", c.getString(c.getColumnIndex("YBMJ")));
                map.put("DKYBMZHJ", c.getString(c.getColumnIndex("DKYBMZHJ")));
                map.put("SZHJ", c.getString(c.getColumnIndex("SZHJ")));
                map.put("SZGJBZ", c.getString(c.getColumnIndex("SZGJBZ")));
                map.put("MKSL", c.getString(c.getColumnIndex("MKSL")));
                map.put("MNJHFYL", c.getString(c.getColumnIndex("MNJHFYL")));
                map.put("TDZK", c.getString(c.getColumnIndex("TDZK")));
                map.put("GGSY", c.getString(c.getColumnIndex("GGSY")));
                map.put("GGFS", c.getString(c.getColumnIndex("GGFS")));
                map.put("ZZ", c.getString(c.getColumnIndex("ZZ")));
                map.put("SZCD", c.getString(c.getColumnIndex("SZCD")));
                map.put("JGQK", c.getString(c.getColumnIndex("JGQK")));
                map.put("JBQK", c.getString(c.getColumnIndex("JBQK")));
                map.put("JSQK", c.getString(c.getColumnIndex("JSQK")));

            }
            c.close();
            db.close();
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 填报保存
     */
    public static boolean sgscSave(Map<String, String> map, String table, String path, boolean isNew) {
        openDataBase(path);
        db.beginTransaction();
        try {

            ContentValues values = new ContentValues();
            if (isNew) {
                values.put("YFBHU", map.get("YFBHU"));
                values.put("DKBHU", map.get("DKBHU"));
                values.put("ZWBH", map.get("ZWBH"));
                values.put("ZWMC", map.get("ZWMC"));
            }
            values.put("YBFYSL", map.get("YBFYSL"));
            values.put("YBMJ", map.get("YBMJ"));
            values.put("DKYBMZHJ", map.get("DKYBMZHJ"));
            values.put("SZHJ", map.get("SZHJ"));
            values.put("SZGJBZ", map.get("SZGJBZ"));
            values.put("MKSL", map.get("MKSL"));
            values.put("MNJHFYL", map.get("MNJHFYL"));
            values.put("TDZK", map.get("TDZK"));
            values.put("GGSY", map.get("GGSY"));
            values.put("GGFS", map.get("GGFS"));
            values.put("ZZ", map.get("ZZ"));
            values.put("SZCD", map.get("SZCD"));
            values.put("JGQK", map.get("JGQK"));
            values.put("JBQK", map.get("JBQK"));
            values.put("JSQK", map.get("JSQK"));

            if (isNew) {
                db.insert(table, "", values);
            } else {
                db.update(table, values, "YFBHU = ? and DKBHU = ? and ZWBH = ?",
                        new String[]{map.get("YFBHU"), map.get("DKBHU"), map.get("ZWBH")});
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }

        return true;
    }

    // ================================

    /**
     * 得到拆分地块编号集合
     *
     * @param path
     * @param table 表名
     * @param key   主键
     * @param value 值
     * @return
     */
    public static List<String> getDKBHList(String path, String table, String filter) {
        openDataBase(path); // 打开数据
        List<String> list = new ArrayList<String>();
        String sql = "";
        if (StringUtil.isEmpty(filter)) {
            sql = "select YFDKBH from " + table;
        } else {
            sql = "select YFDKBH from " + table + " where " + filter;
        }
        System.out.println("-sql-:" + sql);
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            list.add(c.getString(c.getColumnIndex("YFDKBH")));

        }
        c.close();
        db.close();
        return list;
    }

    // ===========================保存地块 图斑类型修订 属性==========================================

    /**
     * 完善样方自然地块 图斑类型修订
     */
    public static void updateTBLXXD(String table, String path, String dkbhu, String tblx) {
        openDataBase(path); // 打开数据
        db.beginTransaction();
        try {
            ContentValues cv = new ContentValues();
            cv.put("TBLXXD", tblx);

            db.update(table, cv, "DKBHU = ?", new String[]{dkbhu});
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
    }

    // =======================================================================

    /**
     * 获取样方图纸集合
     */
    public static List<Map<String, String>> getYFImageListData(String table, List<String> fieldList, String key, Object value,
                                                               String filter, String path) {
        try {
            openDataBase(path); // 打开数据
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            String fstr = "";

            if (fieldList == null || fieldList.size() == 0) {
                fstr = " * ";
                return null;
            } else {
                fieldList.add("rowid");// 主键
                for (String str : fieldList) {
                    fstr += " " + str + ",";
                }
                fstr = fstr.substring(0, fstr.length() - 1);
            }

            String wstr = "";
            if (StringUtil.isNotEmpty(key) && StringUtil.isNotEmpty(value + "")) {
                if (StringUtil.isString(value)) {// 是string
                    wstr = " WHERE " + key + " = '" + value + "'";
                } else {
                    wstr = " WHERE " + key + " = " + value + "";
                }
                if (StringUtil.isNotEmpty(filter)) {
                    wstr += " and " + filter;
                }
            } else {
                if (StringUtil.isNotEmpty(filter)) {
                    wstr = " where " + filter;
                }
            }

            String sql = "SELECT " + fstr + " FROM " + table + " " + wstr + " order by FILENAME ";
            System.out.println("###sql:" + sql);

            Cursor c = db.rawQuery(sql, null);
            while (c.moveToNext()) {
                Map<String, String> map = new HashMap<String, String>();
                for (String str : fieldList) {
                    map.put(str, c.getString(c.getColumnIndex(str)));
                }
                list.add(map);
            }
            c.close();
            db.close();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            // CommenUtil.toast("数据库操作错误，请联系管理员", context);
        }
        return null;
    }

    /**
     * 得到一个样方所有图纸照片名集合
     *
     * @param path
     * @param table 表名
     * @param key   主键
     * @param value 值
     * @return
     */
    public static List<String> getImageNameList(String path, String table, String filter) {
        openDataBase(path); // 打开数据
        List<String> list = new ArrayList<String>();
        String sql;
        if (StringUtil.isEmpty(filter)) {
            sql = "select FILENAME from " + table;
        } else {
            sql = "select FILENAME from " + table + " where " + filter;
        }
        System.out.println("-sql-:" + sql);
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            String img = c.getString(c.getColumnIndex("FILENAME"));
            list.add(img.replace(".jpg", ""));
        }
        c.close();
        db.close();
        return list;
    }

    /**
     * 完善样方图纸位置
     */
    public static void updateYFPosition(String table, String path, String pos, String yfbhu, String dcqb, String type) {
        openDataBase(path); // 打开数据
        db.beginTransaction();
        try {
            ContentValues cv = new ContentValues();
            cv.put("备注", pos);

            db.update(table, cv, "样方编号  = ? and DCQB = ? and TYPE = ?", new String[]{yfbhu, dcqb, type});
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
    }

    //========================创建无人机随机拍摄表===========================

    public static void createSAMPLE(String path, String table) {
        openDataBase(path); // 打开数据
        db.beginTransaction();
        try {
            db.execSQL("CREATE TABLE IF NOT EXISTS " + table
                    + " (PHOTOID VARCHAR2, FILENAME VARCHAR2, LON VARCHAR2,"
                    + " LAT VARCHAR2, DATE VARCHAR2, CUNNAME VARCHAR2,"
                    + " CUNDM VARCHAR2, CYMS VARCHAR2, BZ VARCHAR2, "
                    + "DCQB VARCHAR2, TYPE VARCHAR2, COUNTY VARCHAR2)");
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
    }


    //===========================单一作物统一填报==================================

    /**
     * 单一作物统一填报
     */
    public static void add(String table, String path, String dcq, List<Map<String, String>> dklist, Map<String, String> zw, KeyValueBean tblx, String sslx, String fzcs) {
        openDataBase(path);
        db.beginTransaction();
        try {
            String dkbhus = "";
            for (Map<String, String> dk : dklist) {
                dkbhus += "'" + dk.get("DKBHU") + "',";
            }
            dkbhus = dkbhus.substring(0, dkbhus.length() - 1);
            //删除所有对应地块的填报数据
            db.execSQL("delete from 作物" + dcq + " where DKBHU IN (" + dkbhus + ")");
            db.execSQL("delete from 设施" + dcq + " where DKBHU IN (" + dkbhus + ")");

            //逐条保存
            ContentValues cv = new ContentValues();
            if (zw == null) {//空
                cv.put("SNYD", sslx);
                cv.put("SNFZCS", fzcs);
            } else if (table.contains("作物")) {//作物
                cv.put("ZW", zw.get("ZWMC"));
                cv.put("ZWBH", zw.get("ZWBH"));
                cv.put("ZWLX", tblx.getValue());
            } else if (table.contains("设施")) {//设施
                cv.put("SNZWMC", zw.get("SNZWMC"));
                cv.put("SNZWBH", zw.get("SNZWBH"));
                cv.put("SNFZCS", fzcs);
                cv.put("SNYD", sslx);
            }
            for (Map<String, String> dk : dklist) {

                cv.put("DKBHU", dk.get("DKBHU"));
                cv.put("YFBHU", dk.get("YFBHU"));
                if (table.contains("作物")) {//作物
                    cv.put("PID", dk.get("YFDKBH"));
                    cv.put("ZWMJ", CommenUtil.PFMtoMU(dk.get("TBMJ")));
                } else if (table.contains("设施")) {//设施
                    cv.put("SNZWMJ", CommenUtil.PFMtoMU(dk.get("TBMJ")));
                }
                db.insert(table, "", cv);

                //保存 地块 完成填报标识，完善图斑类型修订
                ContentValues dkcv = new ContentValues();
                dkcv.put("TBLXXD", tblx.getValue() + "(" + tblx.getKey() + ")");
                dkcv.put("COMPLETE", "1");
                db.update("样方自然地块" + dcq, dkcv, "DKBHU = ?", new String[]{dk.get("DKBHU")});
            }

            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
    }
}
